# -*- coding: UTF-8 -*-
# DSOX2024A 示波器
import pyvisa
from pyvisa.constants import *
import xlwt
import time
import os


class Oscilloscope:
    # 打开示波器
    def __init__(self, count):
        rm = pyvisa.ResourceManager()
        tupl = rm.list_resources()
        if len(tupl) <= 0:
            print("can not find port !")
        else:
            self.res = rm.open_resource(tupl[count], AccessModes.no_lock, 3000, None)

    # 测量示波器频率
    def Frequency(self, Freq=100000, volt=3, count=10,
                  delay=100):
        """
        :param Freq: 最大频率
        :param volt: 最大电压
        :param count: count 1~100  样本统计数量
        :param delay: delay 延迟100ms
        :return:
        """
        if Freq < 0 or volt < 0:
            raise Exception(" Frequency loop cycles not is 0")
        try:
            time_string = str(time.strftime('%Y%m%d%H%M%S') + '频率测试')
            dev_string = ('./' + time_string + '.xls').decode('utf-8')
            path = os.path.abspath(dev_string)
            book = xlwt.Workbook(encoding='utf-8', style_compression=0)
            sheet = book.add_sheet("频率测试日志表", cell_overwrite_ok=True)
            sheet.write(0, 0, '频率测试值(A)')
            sheet.write(1, 0, '最大频率值(A)')
            sheet.write(2, 0, '最小频率值(A)')
            sheet.write(3, 0, '平均频率值(A)')
            res = self.ResourceManager()
            res.write('SYSTem:REM')
            res.write('SYSTem:PRESet')
            res.write('*CLS')
            freq_range = 'CONF:FREQ {0}, MAX'.format(Freq)
            volt_range = 'FREQ:VOLT:RANG {0}'.format(volt)
            res.write(freq_range)
            res.write(volt_range)
            res.write('SAMP:COUN %d' % count)
            res.write('TRIG:DELay %f' % (delay / 1000.0))
            time.sleep(count * 0.5)
            res.write('READ?')
            freq_value = res.read()
            freq_result = freq_value.split(',')
            for index in freq_result:
                row = 0
                while (row < count):
                    sheet.write(0, row + 1, index)
                    row = row + 1
            Sum = 0
            for index in freq_result:
                Sum = float(index) + Sum
            avg_value = Sum / len(freq_result)
            max_value = max(freq_result)
            min_value = min(freq_result)
            sheet.write(1, 1, max_value)
            sheet.write(2, 1, min_value)
            sheet.write(3, 1, avg_value)
            book.save(path)
            print("频率测试样本数量=%d 最大值=%s 最小值=%s 平均值=%f" % (count, max_value, min_value, avg_value))
        except Exception as e:
            print (e)
        finally:
            res.write('*CLS')
            res.write('SYSTem:LOCal')
